//https://blog.csdn.net/qq_44981039/article/details/110185982
//https://zhuanlan.zhihu.com/p/347904660
#include "temperature.h"

sbit dht11 = P5^5;

void Delay20ms()		//@11.0592MHz
{
	unsigned char i, j, k;

	i = 2;
	j = 32;
	k = 60;
	do
	{
		do
		{
			while (--k);
		} while (--j);
	} while (--i);
}

void Delay30us()		//@11.0592MHz
{
	unsigned char i;

	_nop_();
	_nop_();
	i = 108;
	while (--i);
}

void Delay1us()		//@11.0592MHz
{
	unsigned char i;

	_nop_();
	_nop_();
	i = 1;
	while (--i);
}

void Delay40us()		//@11.0592MHz
{
	unsigned char i;

	_nop_();
	i = 145;
	while (--i);
}


int dht11_rest_check()
{
    int timer = 0;
    //step1
    EA = 0;
    dht11 = 0;
    Delay20ms();
    //step2
    dht11 = 1;
    Delay30us();
    //step3
    while (!dht11)
    {
        timer++;
        Delay1us();
        if(timer > 100)
        {
            EA = 1;
            return 0;
        }
    }
    if(timer < 20)
    {
        EA = 1;
        return 0;
    }
    //step4
    timer = 0;
    while (dht11)
    {
        timer++;
        Delay1us();
        if(timer > 100)
        {
            EA = 1;
            return 0;
        }
    }
    EA = 1;
    if (timer < 20)
    {
        return 0;
    }
    
    return 1;
}

int dht11_read_byte()
{
    int i;
    int byt = 0;

    EA = 0;
    for(i=0;i<8;i++)
    {
        while(dht11);
        while(!dht11);
        Delay40us();
        byt <<= 1;
        if(dht11)
        {
            byt |= 0x01;
        }
    }
    EA = 1;
    return byt;
}

int dht11_read_data(int *humi,int *temp)
{
    int sta = 0;
    int i;
    int buf[5];

    if(dht11_rest_check())
    {
        for(i=0;i<5;i++)
        {
            buf[i] = dht11_read_byte();
        }
        if(buf[0]+buf[1]+buf[2]+buf[3] == buf[4])
        {
            *humi = buf[0];
            *temp = buf[2];
        }
        sta = 1;
    }
    else
    {
        *humi = 0xff;
        *temp = 0xff;
        sta = 0;
    }
    return sta;
}